package com.tuotu.gps.utils;

import android.bluetooth.BluetoothSocket;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import com.tuotu.gps.entity.LocationEntity;
import com.tuotu.gps.entity.LocationInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * Created by XUYEWEN on 2017/7/23.
 */

public class Utils {
//    private static final double errorDis=0.02;
    public static SimpleDateFormat itemTimeFormat = new SimpleDateFormat("MM-dd HH:mm");//设置日期格式
    private static final String[] strDir = {"北", "东北", "东", "东南", "南", "西南", "西", "西北"};
    public static boolean getSdcard(){
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public static void createGpsFile(final double lon, final double lat, final float bearing, final String name, long time){
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
                File file=new File(name+".txt");
                FileOutputStream os= null;
                try {
                    os = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
//                String temp="lon:"+lon+",lat:"+lat+",direction:"+bearing;
                JSONObject object=new JSONObject();
                try {
//                    object.put("lon",lon);
//                    object.put("lat",lat);
//                    object.put("direction",bearing);
//                    object.put("collect_time",time);
                    object.put("lon",getBase64(String.valueOf(lon)));
                    object.put("lat",getBase64(String.valueOf(lat)));
                    object.put("direction",getBase64(String.valueOf(bearing)));
                    object.put("collect_time",getBase64(String.valueOf(time)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    os.write(object.toString().getBytes());
//                    os.write(getBase64(object.toString()).getBytes());
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        if(null!=os)
                            os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//            }
//        }).start();
    }

    public static void createGpsInfo(String data,String name){
        File file=new File(name+".txt");
        FileOutputStream os= null;
        try {
            os = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String temp="data:"+data;
        try {
            os.write(temp.getBytes());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteFile(String name){
        try {
            File file1=new File(name+".mp3");
            if (file1.exists()){
                file1.delete();
            }
            File file2=new File(name+".txt");
            if (file2.exists()){
                file2.delete();
            }
        }catch (Exception e){
            Log.i("xyw","删除失败");
        }
    }

    public static void deleteAllNOUploadFile(final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(path);
                if (file.length()>0){
                    File[] files = file.listFiles();
                    if(null==files){
                        return ;
                    }
                    for (File file1:files) {
                        if (file1.isDirectory()){
                            deleteAllNOUploadFile(file1.getPath());
                            file1.delete();
                        }else{
                            file1.delete();
                        }
                    }
                }
            }
        }).start();
    }

    public static void deleteHasPostFile(final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file1=new File(path);
                if (file1.exists()){
                    file1.delete();
                }
            }
        }).start();
    }

    public static String readFile(String path){
        File file=new File(path);
        if(!file.exists()){
            return "";
        }

        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(new FileInputStream(path), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuilder sb = new StringBuilder("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null!=inputStreamReader)
                    inputStreamReader.close();
                if(null!=reader)
                    reader.close();
            } catch (IOException e) {
                    e.printStackTrace();
            }

        }
        return sb.toString();
    }

    public static void saveLocationEntity(final String mFilename,final ArrayList<LocationEntity> entity) throws JSONException,
            IOException {
                JSONArray array = new JSONArray();
                for (LocationEntity c : entity){
                    try {
                        array.put(c.toJSON());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                Writer writer = null;
                try {
                    File file=new File(mFilename);
                    OutputStream out = new FileOutputStream(file);
                    writer = new OutputStreamWriter(out);
                    writer.write(getBase64(array.toString()));
                } catch (IOException e){

                }finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
    }

    /**
     * 移动指定文件或文件夹(包括所有文件和子文件夹)
     *
     * @param from
     *            要移动的文件或文件夹
     * @param to
     *            目标文件夹
     * @throws Exception
     */
    public static void MoveFolderAndFileWithSelf(String from, String to) throws Exception {
        try {
            File dir = new File(from);
            // 目标
            to +=  File.separator + dir.getName();
            File moveDir = new File(to);
            if(dir.isDirectory()){
                if (!moveDir.exists()) {
                    moveDir.mkdirs();
                }
            }else{
                File tofile = new File(to);
                dir.renameTo(tofile);
                return;
            }

            //System.out.println("dir.isDirectory()"+dir.isDirectory());
            //System.out.println("dir.isFile():"+dir.isFile());

            // 文件一览
            File[] files = dir.listFiles();
            if (files == null)
                return;

            // 文件移动
            for (int i = 0; i < files.length; i++) {
                LogUtil.print("文件名："+files[i].getName());
                if (files[i].isDirectory()) {
                    MoveFolderAndFileWithSelf(files[i].getPath(), to);
                    // 成功，删除原文件
                    files[i].delete();
                }
                File moveFile = new File(moveDir.getPath() + File.separator + files[i].getName());
                // 目标文件夹下存在的话，删除
                if (moveFile.exists()) {
                    moveFile.delete();
                }
                files[i].renameTo(moveFile);
            }
            dir.delete();
        } catch (Exception e) {
            throw e;
        }
    }

    public static String getDirection(double b) {
        int dir = (int) ((b + 22.5) / 45) % 8;
        return strDir[dir];
    }

    // 加密
    public static String getBase64(String str) {
        String result = "";
        if( str != null) {
            try {
                result = new String(Base64.encode(str.getBytes("utf-8"), Base64.DEFAULT),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // 解密
    public static String getFromBase64(String str) {
        String result = "";
        if (str != null) {
            try {
                result = new String(Base64.decode(str, Base64.DEFAULT), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
